package com.lagou.web.servlet;

import com.lagou.utils.UUIDUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("utf-8");
            //是否是文件上传表单
            boolean multipartContent = upload.isMultipartContent(req);
            if (multipartContent) {
                List<FileItem> list = upload.parseRequest(req);
                if (list != null) {
                    for (FileItem item : list) {
                        boolean formField = item.isFormField();
                        if (formField) {
                            String fieldName = item.getFieldName();
                            String fieldValue = item.getString("utf-8");
                            System.out.println(fieldName + "=" + fieldValue);
                        } else {
                            String fileName = item.getName();
                            String newFileName = UUIDUtils.getUUID() + "_" + fileName;
                            InputStream in = item.getInputStream();

                            String contextPath = this.getServletContext().getContextPath();
                            String uploadPath = contextPath + "/upload";
                            File file = new File(uploadPath);
                            if (!file.exists()) {
                                file.mkdir();
                            }
                            String fullPath = uploadPath + "/" + newFileName;
                            FileOutputStream out = new FileOutputStream(fullPath);
                            IOUtils.copy(in, out);
                            out.close();
                            in.close();
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
